using System.ComponentModel.DataAnnotations;

namespace AiPlatformAdmin.Api.Models;

public enum UserRole
{
    AppUser,
    PlatformUser,
    Administrator,
    SystemAdministrator
}

public class User : ITenantEntity
{
    public int Id { get; set; }

    [Required]
    public int TenantId { get; set; }

    [Required]
    [MaxLength(100)]
    public string Username { get; set; } = string.Empty;

    [Required]
    [EmailAddress]
    [MaxLength(200)]
    public string Email { get; set; } = string.Empty;

    [Required]
    public string PasswordHash { get; set; } = string.Empty;

    [Required]
    [MaxLength(500)]
    public string Roles { get; set; } = string.Empty; // Comma-separated roles: "PlatformUser,Administrator"

    public DateTime CreatedAt { get; set; } = DateTime.UtcNow;

    public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;

    // Navigation properties
    public Tenant? Tenant { get; set; }
    public ICollection<UserTeam> UserTeams { get; set; } = new List<UserTeam>();
    public ICollection<TokenUsage> TokenUsages { get; set; } = new List<TokenUsage>();
    public ICollection<TeamAdmin> TeamAdmins { get; set; } = new List<TeamAdmin>();
    public ICollection<KnowledgeBaseAdmin> KnowledgeBaseAdmins { get; set; } = new List<KnowledgeBaseAdmin>();
    public ICollection<AgentAdmin> AgentAdmins { get; set; } = new List<AgentAdmin>();

    // Helper methods for role management
    public List<UserRole> GetRoles()
    {
        if (string.IsNullOrWhiteSpace(Roles))
            return new List<UserRole>();

        return Roles.Split(',', StringSplitOptions.RemoveEmptyEntries)
            .Select(r => Enum.Parse<UserRole>(r.Trim()))
            .ToList();
    }

    public void SetRoles(IEnumerable<UserRole> roles)
    {
        Roles = string.Join(",", roles.Select(r => r.ToString()));
    }

    public bool HasRole(UserRole role)
    {
        return GetRoles().Contains(role);
    }

    public bool HasAnyRole(params UserRole[] roles)
    {
        var userRoles = GetRoles();
        return roles.Any(r => userRoles.Contains(r));
    }
}
